<!-- views/student/RecordForm.vue -->
<template>
  <div class="record-form">
    <el-page-header @back="goBack" :content="holidayName + '去向登记'" class="page-header" />

    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="main-form"
    >
      <el-form-item label="去向类型" prop="travelType">
        <el-radio-group v-model="form.travelType">
          <el-radio :label="0">离校</el-radio>
          <el-radio :label="1">留校</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 离校表单 -->
      <div v-if="form.travelType === 0">
        <el-form-item label="去向地址" prop="address">
          <div class="address-container">
            <el-cascader
                :options="regionOptions"
                v-model="form.address"
                placeholder="请选择省市区"
                style="width: 100%;"
            />
          </div>
        </el-form-item>

        <el-form-item label="详细地址" prop="addressDetail">
          <el-input
              v-model="form.addressDetail"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-form-item label="离校时间" prop="leaveTime">
          <el-date-picker
              v-model="form.leaveTime"
              type="datetime"
              placeholder="选择离校时间"
              value-format="yyyy-MM-dd HH:mm"
              style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="返校时间" prop="returnTime">
          <el-date-picker
              v-model="form.returnTime"
              type="datetime"
              placeholder="选择返校时间"
              value-format="yyyy-MM-dd HH:mm"
              style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input
              v-model="form.emergencyContact"
              placeholder="请输入紧急联系人姓名"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="emergencyPhone">
          <el-input
              v-model="form.emergencyPhone"
              placeholder="请输入联系电话"
          />
        </el-form-item>
      </div>

      <!-- 留校表单 -->
      <div v-else>
        <el-alert
            title="留校说明"
            type="info"
            description="留校期间请遵守学校管理规定，注意人身财产安全。"
            show-icon
            style="margin-bottom: 20px;"
        />
      </div>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          提交登记
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      holidayName: '',
      form: {
        travelType: 0, // 0-离校，1-留校
        address: [], // 省市区ID
        addressDetail: '',
        leaveTime: '',
        returnTime: '',
        emergencyContact: '',
        emergencyPhone: ''
      },
      regionOptions: [
        {
          value: 520000,
          label: '贵州省',
          children: [
            {
              value: 522700,
              label: '黔南州',
              children: [
                { value: 522701, label: '都匀市' },
                { value: 522702, label: '福泉市' },
                { value: 522722, label: '荔波县' },
                { value: 522723, label: '贵定县' },
                { value: 522725, label: '瓮安县' },
                { value: 522726, label: '独山县' },
                { value: 522727, label: '平塘县' },
                { value: 522728, label: '罗甸县' },
                { value: 522729, label: '长顺县' },
                { value: 522730, label: '龙里县' },
                { value: 522731, label: '惠水县' },
                { value: 522732, label: '三都县' }
              ]
            }
          ]
        },
        {
          value: 440000,
          label: '广东省',
          children: [
            {
              value: 440100,
              label: '广州市',
              children: [
                { value: 440103, label: '荔湾区' },
                { value: 440104, label: '越秀区' },
                { value: 440105, label: '海珠区' },
                { value: 440106, label: '天河区' },
                { value: 440111, label: '白云区' },
                { value: 440112, label: '黄埔区' },
                { value: 440113, label: '番禺区' },
                { value: 440114, label: '花都区' },
                { value: 440115, label: '南沙区' },
                { value: 440117, label: '从化区' },
                { value: 440118, label: '增城区' }
              ]
            }
          ]
        }
      ],
      submitting: false
    };
  },
  mounted() {
    // 从路由参数获取假期信息
    this.holidayName = this.$route.query.holidayName || '假期';
  },
  computed: {
    /**
     * 表单验证规则
     */
    rules() {
      return {
        travelType: [{ required: true, message: '请选择去向类型', trigger: 'change' }],
        address: this.form.travelType === 0 ?
            [{ required: true, message: '请选择去向地址', trigger: 'change' }] : [],
        addressDetail: this.form.travelType === 0 ?
            [{ required: true, message: '请输入详细地址', trigger: 'blur' }] : [],
        leaveTime: this.form.travelType === 0 ?
            [{ required: true, message: '请选择离校时间', trigger: 'change' }] : [],
        returnTime: this.form.travelType === 0 ?
            [{ required: true, message: '请选择返校时间', trigger: 'change' }] : [],
        emergencyContact: this.form.travelType === 0 ?
            [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }] : [],
        emergencyPhone: this.form.travelType === 0 ? [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ] : []
      };
    }
  },
  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      this.$router.back();
    },

    /**
     * 提交表单
     */
    async submitForm() {
      try {
        // 1. 表单验证
        await this.$refs.formRef.validate();

        // 2. 设置加载状态
        this.submitting = true;

        // 3. 准备提交数据
        const submitData = {
          holidayId: Number(this.$route.query.holidayId),
          travelType: this.form.travelType,
          province: '',
          city: '',
          county: '',
          addressDetail: this.form.addressDetail,
          leaveTime: this.form.leaveTime,
          returnTime: this.form.returnTime,
          emergencyContact: this.form.emergencyContact,
          emergencyPhone: this.form.emergencyPhone
        };

        // 4. 如果选择了地址，解析省市区
        if (this.form.travelType === 0 && this.form.address.length === 3) {
          const province = this.regionOptions.find(p => p.value === this.form.address[0]);
          const city = province?.children?.find(c => c.value === this.form.address[1]);
          const county = city?.children?.find(co => co.value === this.form.address[2]);

          if (province && city && county) {
            submitData.province = province.label;
            submitData.city = city.label;
            submitData.county = county.label;
          }
        }

        // 5. 调用API提交
        await $studentAPI.submitRecord(submitData);

        // 6. 提交成功
        this.$message.success('去向登记成功');
        this.$router.push('/student/record');
      } catch (err) {
        console.error('提交失败', err);
        this.$message.error('提交失败，请重试');
      } finally {
        // 7. 重置加载状态
        this.submitting = false;
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.$refs.formRef.resetFields();
    }
  }
};
</script>